from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import OrderModel
from .serializers import OrderModelSer
from goods.serializers import SKUSer
# Create your views here.

class AllView(APIView):
    def get(self,request):
        order = OrderModel.objects.all()
        list1 = []
        for i in order:
            list1.append({
                'order_id':i.order_id,
                'created_time':i.created_time,
            })

        count = order.count()

        return Response({'msg':'加载成功','code':200,'data':list1,'count':count})



# 获取详情信息
class InfoView(APIView):
    def get(self,request,id):
        try:
            order = OrderModel.objects.get(order_id=id)
        except Exception as e:
            print('获取信息失败',e)
            return Response({
                'code':400,
                'msg':'获取信息失败'
            })

        sku_goods = order.skus.all()

        skus = []
        for sku_good in sku_goods:
            sku_order = sku_good.sku
            count = sku_good.count

            ser_sku = SKUSer(sku_order)

            sku_dict = ser_sku.data

            sku_dict['count'] = count

            skus.append(sku_dict)

        ser = OrderModelSer(order)

        order_dict = ser.data

        order_dict['skus'] = skus

        return Response({'message':"获取详情成功","data":order_dict})

    # 修改状态
    def put(self,request,id):
        status = request.data.get('status')
        try:
            OrderModel.objects.filter(order_id=id).update(status=status)
            return Response({
                'code':200,
                'msg':'修改成功'
            })
        except Exception as e:
            print('修改错误',e)
            return Response({
                'code':400,
                'msg':'修改失败'
            })